﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace mssql.t4
{
	public class TempSqlTable
	{
		public readonly string ConnectionString;
		public readonly string Sql;

		public TempSqlTable(string connectionString, string sql)
		{
			ConnectionString = connectionString;
			Sql = sql;
		}

		private string DbName { get; set; }


		public string Build()
		{
			using (SqlConnection connection = new SqlConnection(ConnectionString))
			{
				DbName = connection.Database;
				using (SqlCommand command = new SqlCommand()
					                            {
						                            CommandType = CommandType.Text,
						                            Connection = connection,
						                            CommandText = Sql,
					                            })
				{


					SqlDataAdapter adapter = new SqlDataAdapter(command);
					DataSet ds = new DataSet();
					adapter.Fill(ds);

					List<BaseDataColumn> list = new List<BaseDataColumn>(ds.Tables[0].Columns.Count);
					foreach (DataColumn col in ds.Tables[0].Columns.Cast<DataColumn>())
					{
						list.Add(BaseDataColumn.Factory(col));
					}

					return Generate(list);

				}
			}

		}

		private string Generate(List<BaseDataColumn> columns)
		{
			StringBuilder sb = new StringBuilder();

			sb.AppendLine("USE [" + DbName + "]");
			sb.AppendLine("GO");

			sb.AppendLine();

			sb.AppendLine("DECLARE @tempTable TABLE");
			sb.AppendLine("(");

			for (int i = 0; i < columns.Count; i++)
			{
				sb.Append(columns[i]);
				if (columns.Count - 1 != i)
					sb.Append(",");
				sb.AppendLine();
			}

			sb.AppendLine(")");

			sb.AppendLine();

			sb.AppendLine("INSERT INTO @tempTable");
			sb.AppendLine(Sql);


			return sb.ToString();
		}
	}
}